<?php

namespace api\modules\backend\controllers;

use api\modules\backend\models\Account;
use yii;
use yii\filters\auth\QueryParamAuth;
use common\commands\VtCommon;

/**
 * Account Controller API
 *
 * @author Fong <xiaofeng.zhang>
 */
class AccountController extends ControllerBase
{
    public $modelClass = 'api\modules\backend\models\Account';

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => QueryParamAuth::className(),
            'optional' => [
                'index'
            ],
        ];
        $behaviors['authenticator']['except'] = ['options'];
        return $behaviors;
    }

    /**
     * 登录
     * @throws yii\base\Exception
     */
    public function actionIndex()
    {
        $data = [];

        $request = Yii::$app->request->get();

        $account = $request['userName'];
        $password = $request['password'];
        $data['type'] = $request['type'];

        $modelClass = $this->modelClass;

        $items = $modelClass::find()->from('{{%admin}}')->select(['id', 'api_token', 'api_token_expire'])
            ->where(['account' => $account, 'password' => md5($password)])
            ->asArray()
            ->one();

        if (!empty($items)) {
            if ($items['api_token_expire'] < time()) {
                $accountModel = Account::findOne($items['id']);
                $accountModel->generateApiToken();

                $tr = Yii::$app->db->beginTransaction();
                try {

                    $accountModel->id = $items['id'];

                    $accountModel->save();

                    $tr->commit();
                } catch (\Exception $e) {
                    $tr->rollBack();
                    $this->response(VtCommon::getPackedResponse(DATABASE_FAILED, Yii::t('app', 'DATABASE_FAILED'), null));
                }
            }

            $data['currentAuthority'] = 'admin';
            $data['token'] = $items['api_token'];
            $this->success($data);
        }

        $this->response(VtCommon::getPackedResponse(DATABASE_FAILED, Yii::t('app', 'Account_Or_Password_Error'), $data));
    }

    /**
     * 获取信息
     */
    public function actionInfo()
    {
        $accessToken = Yii::$app->request->get();

        $user = Account::findOne(['api_token' => $accessToken, 'status' => 1]);

        $data = [
            'name' => $user->account,
            'user_id' => $user->id,
            'avatar' => $user->avatar,
            'notifyCount' => 0
        ];

        $this->success($data);
    }
}